package com.fwj.common.util;

import com.alibaba.fastjson.JSONObject;
import com.fwj.common.entity.Code;
import com.fwj.common.model.CodeVo;

import java.util.ArrayList;
import java.util.Deque;
import java.util.LinkedList;
import java.util.List;

/**
 * @Author: fwj
 * @Data: 2022/4/25 18:27
 * @Version 1.0
 * @Description:
 */


public class CodeUtil {

    /**
     * list 转多叉树。用队列实现
     * 对于该方法优化，可以想到的是在分配分类ID的时候有序分类ID值，正序排序，然后读入，就能避免重复扫描(现在的方法时间复杂度大)
     */
    public static CodeVo codeListConverTree(List<Code> codeList) throws Exception {
        CodeVo codeVo = new CodeVo();
        int size = codeList.size();
        Deque deque = new LinkedList();

        //读入根节点
        for (int i = 0; i < size; i++) {
            Code code = codeList.get(i);
            if (code.getParentId() == -1) {
                CodeVo headCodeVo = JSONObject.parseObject(JSONObject.toJSONString(code), CodeVo.class);
                deque.offerLast(headCodeVo);
                codeVo = headCodeVo;
                break;
            }
        }

        //构建树
        while (!deque.isEmpty()) {
            //弹出队列首元素，构建子树
            CodeVo codeVo1 = (CodeVo) deque.pollFirst();
            for (int i = 0; i < size; i++) {
                Code code1 = codeList.get(i);
                //如果当前Code是当前弹出元素的子树，则构建子树
                if (code1.getParentId().equals(codeVo1.getCodeId())) {
                    if (codeVo1.getChildCode() == null) {
                        codeVo1.setChildCode(new ArrayList<>());
                    }
                    //增加当前树的子树，并压入队列
                    CodeVo codeVo2 = JSONObject.parseObject(JSONObject.toJSONString(code1), CodeVo.class);
                    deque.offerLast(codeVo2);
                    codeVo1.getChildCode().add(codeVo2);
                }
            }
        }
        return codeVo;
    }
}
